package models

import (
	"fmt"
	"strings"
)

type Paper struct {
	Model
	Content string `json:"content"`
	Show	int8   `json:"show"`
	Year    int 	`json:"year"`
}


func ExistPaperByID(id int) bool {
	var paper Paper
	db.Select("id").Where("id = ?", id).First(&paper)
	return paper.ID > 0
}

func GetPapers() (papers []Paper) {
	db.Find(&papers)
	return
}

func AddPaper(papers *[]Paper) bool {
	var sb strings.Builder
	sb.WriteString("insert into `qt_paper` (`content`, `show`, `year`) values ")

	for i, paper := range *papers {
		content := strings.Replace(paper.Content, "'", "\\'", -1)
		if i == len(*papers) - 1 {
			sb.WriteString(fmt.Sprintf("('%s','%d',%d);",content, paper.Show, paper.Year))
		} else {
			sb.WriteString(fmt.Sprintf("('%s','%d',%d),", content, paper.Show, paper.Year))
		}
	}
	db.Exec(sb.String())
	return true
}

func DeletePaper(id int) bool {
	db.Where("id = ?", id).Delete(&Paper{})
	return true
}

func UpdatePaper(id int, data interface{}) bool {
	db.Model(&Paper{}).Where("id = ?", id).Updates(data)
	return true
}